<?php
namespace WMApi\Controller;

use Think\Controller;
use Com\Alipay\AlipayNotify;
use Think\Log;
use Think\Model;

use SDXApi\Model\PaymentModel;
use WMApi\Service\OrderService;

/**
 * 外卖_支付宝回调类
 * 
 * @author ^2_3^
 *
 */
class WmalipaynotifyController extends Controller {
    
    private $pay_config;
    
    public function alipay_native_notifypay() {
        $this->pay_config = $this->get_scan_pay_config();
        $this->alipay_notifypay();
    }
    
    private function get_scan_pay_config() {
        $ROOT =  str_replace('\\','/',realpath(dirname(__FILE__).'/../../').'/');
        
        $array = array (
            'seller_id' => '2088811720960505',
            'partner' => '2088811720960505',
            'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',
            'transport' => 'http',
            'app_id' => "2016051601404277",
            'ali_public_key_path' => $ROOT . "api/scan_key/alipay_rsa_public_key.pem",
            'merchant_private_key' => $ROOT . "api/scan_key/rsa_private_key.pem",
            // 'merchant_public_key_file' => $ROOT . "api/scan_key/rsa_public_key.pem",
            // 'ali_public_key_path' => $ROOT . "api/scan_key/rsa_public_key.pem",
            'charset' => "utf-8",
            'sign_type'=>'RSA',
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //最大查询重试次数
            'MaxQueryRetry' => "10",
            //查询间隔
            'QueryDuration' => "3"
        );
        
        return $array;
    }
    
    public function alipay_notifypay() {
        set_time_limit(0);
        
//         $str_post = '
//             {
//                 "payment_type": "1",
//                 "trade_no": "2017091421001004790296282046",
//                 "subject": "\u98df\u5f97\u9c9c-\u8ba2\u5355\u652f\u4ed8:0.01",
//                 "buyer_email": "13680154257@163.com",
//                 "gmt_create": "2017-09-14 15:09:17",
//                 "notify_type": "trade_status_sync",
//                 "quantity": "1",
//                 "out_trade_no": "1709141506130797309s2",
//                 "seller_id": "2088811720960505",
//                 "notify_time": "2017-09-14 15:33:45",
//                 "body": "\u98df\u5f97\u9c9c-\u8ba2\u5355\u652f\u4ed8",
//                 "trade_status": "TRADE_SUCCESS",
//                 "is_total_fee_adjust": "N",
//                 "total_fee": "0.01",
//                 "gmt_payment": "2017-09-14 15:09:18",
//                 "seller_email": "admin@shidexian.com",
//                 "price": "0.01",
//                 "buyer_id": "2088422212349797",
//                 "notify_id": "3891c91aa71798ad950ecdbf4fe326am3i",
//                 "use_coupon": "N",
//                 "sign_type": "MD5",
//                 "sign": "a98b967fb4d8ff90ec43a2d789d81b3b"
//             }
//         ';
//         $_POST = json_decode($str_post, true);
        
        /// 回调开始
self::wm_log('  ');
self::wm_log('支付宝通知处理--- --- --START-- --- ---');
        $arr_arg = $_POST;
        $str_arg = json_encode($arr_arg);
self::wm_log( "POST参数: {$str_arg}" );
        
        $config = $this->pay_config;
        if( empty($config) ) {
            $config = $this->get_app_config();
            
            if($_POST['sign_type'] && $_POST['sign_type']!=$config['sign_type']){
                $config = $this->get_config();
            }
        }
        
        $alipayNotify = new AlipayNotify($config);
        $verify_result = $alipayNotify->verifyNotify();
        
        if( $verify_result ) {//验证成功
            $out_trade_no = $_POST['out_trade_no']; //商户订单号;
            $trade_no = $_POST['trade_no']; //支付宝交易号;
            $trade_status = $_POST['trade_status']; //交易状态;
            
            if( $_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS' ) {
                $out_trade_db = explode("s",$out_trade_no);
                
                /// 充值回调修改
                if( $out_trade_db[1] == PAY_SURPLUS ) {///NO
                    $payment_m = new PaymentModel();
                    $flag_update = $payment_m->updata_recharg_log($out_trade_db[0]);    //更新支付状态;TODO
                    
                    if( $flag_update ){
                        $_POST['out_trade_no'] = $out_trade_db[0];
                        $payment_m->update_alipay_log($_POST,PAY_SURPLUS);
                        
                        echo "success";
                    }else{
                        echo "fail";
                    }
                    
                /// 外卖支付
                }else if( $out_trade_db[1] == PAY_WM_ORDER ) {
                    /// 订单及支付信息
                    $order_service = new OrderService();
                    $order_pay_info = $order_service->get_pay_log( $out_trade_db[0], $out_trade_db[1] );
// self::wm_log("订单支付信息 ".json_encode($order_pay_info));
                    
                    if(empty($_POST["total_fee"]) && !empty($_POST['total_amount'])){
                        $_POST["total_fee"] = $_POST['total_amount'];
                    }
                    
                    /// 混合支付
                    if( $_POST["total_fee"] < $order_pay_info["order_amount"] ) {
                        $surplus['user_id'] = $order_pay_info['uid'];
                        $surplus['amount'] = $_POST["total_fee"];
                        $surplus['process_type'] = 0;
                        $surplus['user_note'] = "交易流水号: {$trade_no}";
                        $surplus['payment'] = '支付宝';
                        $surplus['admin_note'] = '混合支付';
                        
                        $payment_m = new PaymentModel();
                        /// (1)、插入充值记录;
                        $p_log_id = $payment_m->add_recharge_log($surplus, $_POST["total_fee"]);
                        /// (2)、更新充值记录;
                        $flag_update = $payment_m->updata_recharg_log( $p_log_id );
                        
                        if( $flag_update ){
                            $_POST['out_trade_no'] = $p_log_id;
                            /// (3)、完善支付日志;
                            $payment_m->update_alipay_log($_POST,PAY_SURPLUS);
                            /// (4)、余额支付;
                            $order_service->tobalance_pay($out_trade_db[0]);
                            
                            echo "success";
                        }else {
                            echo "fail";
                        }
                        
                    /// 全额支付
                    } else {
                        $result_pay = $order_service->order_paid($out_trade_db[0], ORDER_STATUS_PAYED, PAY_WM_ORDER, $_POST);
                        
                        if( $result_pay['status'] ) {
                            echo "success";
                        }else {
                            echo "fail";
                        }
                    }
                    
                }
            }
            
        }else {
            //验证失败
            echo "fail";
            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
        
self::wm_log('支付宝通知处理--- --- --END-- --- ---');
    }
    
    private function get_config($pay_id){
        $array = array(
            'seller_id' => '2088811720960505',                                          //合作身份者ID
            'partner' => '2088811720960505',                                            //合作身份者ID
            'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
            'transport' => 'http',
            'payment_type' => '1',
            'service' => 'alipay.wap.create.direct.pay.by.user',
            'sign_type' => strtoupper('MD5'),
            'input_charset' => strtolower('utf-8')
        );
        return $array;
    }
    
    private function get_app_config(){
        $ROOT =  str_replace('\\','/',realpath(dirname(__FILE__).'/../../').'/');
        
        $array = array(
            'seller_id' => 'admin@shidexian.com',                                          //合作身份者ID
            'partner' => '2088811720960505',                                            //合作身份者ID
            'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
            'transport' => 'http',
            'payment_type' => '1',
            'service' => 'mobile.securitypay.pay',
            'sign_type' => strtoupper('RSA'),
            'input_charset' => strtolower('utf-8'),
            'private_key_path'=>$ROOT.'api/key_old/rsa_private_key.pem',
            'ali_public_key_path'=>$ROOT.'api/key_old/alipay_rsa_public_key.pem'
        );
        
        return $array;
        
    }
    
    /**
     * 获取阿里云配置（外部继承调用）
     * Created By caicm
     * @return array
     */
    public function get_aliyun_config(){
        $config = $this->pay_config;
        if(empty($config)){
            $config = $this->get_app_config();
            if($_POST['sign_type'] && $_POST['sign_type']!=$config['sign_type']){
                $config = $this->get_config();
            }
        }
        return $config;
    }
    
    /**
     * 写入本地记录
     * 
     * @param $text
     * @param string $filename
     */
    private function wm_log($text, $filename='wm_alipay_log'){
        $text = self::characet($text);
        $open = fopen($filename.".txt", "a" );
        fwrite($open, "[".date("Y-m-d H:i:s")."] ".$text."\r\n");
        fclose($open);
    }
    private function characet($data) {
    	if ( !empty( $data ) ) {
    	    // mb_detect_encoding — 检测字符的编码;
    		$fileType = mb_detect_encoding ( $data, array (
    				'UTF-8',
    				'GBK',
    				'GB2312',
    				'LATIN1',
    				'BIG5' 
    		) );
    		if ($fileType != 'UTF-8') {
    		    // mb_convert_encoding — 转换字符的编码
    			$data = mb_convert_encoding ( $data, 'UTF-8', $fileType );
    		}
    	}
    	return $data;
    }
    
}